package y_2025.m11.d12;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReentrantReadWriteLockExample {
    private final Map files;  // 虚拟文件系统中的文件
    private final ReentrantReadWriteLock lock;  // 读写锁

    public ReentrantReadWriteLockExample() {
        files = new HashMap<>();
        lock = new ReentrantReadWriteLock();
    }

    public String readFile(String fileName) {
        // 获取读锁, 允许多个线程同时读
        lock.readLock().lock();

        try {
            System.out.println("Reading file: " + fileName);
            // 模拟读取文件的耗时操作
            Thread.sleep(1000);
            return (String) files.getOrDefault(fileName, null);
        } catch (InterruptedException e) {
            e.printStackTrace();
            return null;
        } finally {
            // 释放读锁
            lock.readLock().unlock();
        }
    }

    public void writeFile(String fileName, String content) {
        // 获取写锁, 允许一个线程独占写
        lock.writeLock().lock();
        try {
            System.out.println("Writing file: " + fileName);
            // 模拟写入文件的耗时操作
            Thread.sleep(1000);
            files.put(fileName, content);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 释放写锁
            lock.writeLock().unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantReadWriteLockExample fileSystem = new ReentrantReadWriteLockExample();

        // 开启十个写线程
        for (int i = 0; i < 10; ++i) {
            int finalI = i;
            new Thread(() -> {
                fileSystem.writeFile("file" + finalI, "Hello, World!");
            }).start();
        }

        // 开启四个读线程
        for (int i = 0; i < 4; ++i) {
            int finalI = i;
            new Thread(() -> {
                String content = fileSystem.readFile("file" + finalI);
                System.out.println("Read content: " + content);
            }).start();
        }

    }
}
